package batframework.mvc.render;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import batframework.code.util.Assert;
import batframework.mvc.exception.RenderException;

/**
 * 
 * @author bmyues
 */
public class TextRender extends AbstractRender
{
	private final static String contentType = "text/plain";
	
	private String content;

	public void render()
	{
		response.setContentType(getContentType());
		PrintWriter writer  = null;
		try{
			writer = response.getWriter();
			writer.write(content);
		} catch (IOException e){
			throw new RenderException(e);
		}finally{
			if(writer != null){
				writer.flush();
				writer.close();
			}
		}
	}
	
	/**
	 * 
	 * @author bmyues
	 * @return
	 */
	public String getContentType()
	{
		return contentType;
	}
	
	/**
	 * 
	 * @author bmyues
	 * @param content
	 */
	public void setContent(String content)
	{
		this.content = content;
	}
	
	
	/**
	 * 
	 * @ author bmyues
	 * @param content
	 */
	public TextRender(String content)
	{
		super();
		this.content = content;
	}
	
	/**
	 * 
	 * @ author bmyues
	 * @param inputStream
	 */
	public TextRender(InputStream inputStream)
	{
		Assert.notNull(inputStream);
		byte[] bytes = new byte[1024];
		int len = 0;
		StringBuilder sb = new StringBuilder();
		try{
			while((len = inputStream.read(bytes))!= -1)
				sb.append(new String(bytes,0,len));
			this.content = sb.toString();
		} catch (IOException e){
			e.printStackTrace();
		}finally{
			if(inputStream != null){
				try{
					inputStream.close();
				} catch (IOException e){
					e.printStackTrace();
				}
			}
		}
	}

	public TextRender()
	{
		super();
	}
}
